<template>
  <div>
    <CostItem v-loading="loading" :cost-list="costList" :is-invite="detailData.isInvite" />
  </div>
</template>

<script>
import { getSupplierCost } from '@/api/supplier';
import ElMessage from '@/utils/message';
// components
import CostItem from '../costItem';

export default {
  components: { CostItem },
  props: {
    detailData: {
      type: Object,
      default: () => { return {}; }
    },
    selectCostList: {
      type: Array,
      default: () => { return []; }
    }
  },
  data() {
    return {
      costList: [],
      loading: false
    };
  },
  created() {
    this.getCost();
  },
  methods: {
    getResult() {
      return new Promise((resolve, reject) => {
        const selectCostList = [];
        let costOrder = 0;
        let costNum = 0;
        this.costList.forEach(i => {
          if (i.check) {
            selectCostList.push(i);
            costOrder += i.costOrder;
            costNum += i.costNum;
          }
        });
        if (selectCostList.length === 0) {
          ElMessage.error('请选择成本');
          return reject();
        }
        if (costOrder === 0 && costNum === 0) {
          this.$confirm('当前成本结算没有符合要求的订单或者成本，是否继续？', '', {
            confirmButtonText: '继续',
            cancelButtonText: '取消',
            type: 'warning',
            lockScroll: false,
            center: true,
            customClass: 'del-message del-message-cancel',
            iconClass: 'del-icon'
          }).then(() => {
            resolve(selectCostList);
          }).catch(() => {
            reject();
          });
        } else {
          resolve(selectCostList);
        }
      });
    },
    getCost() {
      this.loading = true;
      const params = {
        id: this.detailData.supplierId,
        costBelong: this.detailData.costBelong
        // settleId: this.detailData.id
      };

      if (this.detailData.isInvite) {
        params.isInvite = true;
      }
      getSupplierCost(params).then(res => {
        this.loading = false;
        if (res.code === 200) {
          // this.costList = this.excludeCost(res.data);
          this.costList = res.data;
          this.setSelectedCost();
        }
      });
    },
    // 排除已选择的成本项
    excludeCost(costList) {
      const selectCost = this.detailData.selectCost || [];
      if (selectCost.length) {
        const ids = selectCost.map(i => i.id);
        return costList.filter(it => {
          return !ids.includes(it.id);
        });
      }
      return costList;
    },
    setSelectedCost() {
      const selectCost = this.selectCostList || [];
      if (selectCost.length) {
        const ids = selectCost.map(i => i.id);
        this.costList.forEach(it => {
          if (ids.includes(it.id)) {
            it.check = true;
          }
        });
      }
    }
  }
};
</script>
<style scoped lang="scss">

</style>
